<?php
/**
 * @Author:      lyt
 * @DateTime:    2016-06-03 10:06:58
 * @Description: 用于生成每个门店的 期初 期末库存的 脚本     每天下午四点运行  
 */
/**
 * @Author:      lyt
 * @DateTime:  2017-06-23 10:32:28
 * @Description: 每天下午脚本修改为每天凌晨 跑前一天的
 */
$api_service_path = __DIR__ . "/../../../api/";
ob_start();
require_once($api_service_path . "public/index.php");
ob_end_clean();
DB::connection()->disableQueryLog(); 

$input_1 = array(
    'item_type'     => 0,                     
    'item_id'       => 0,     
    'shop_id'       => 0,  
    'date'          => date("Y-m-d",time()-86400),
    'data_id'       => NULL,
    'number'        => NULL,
    'amount'        => NULL,
    'created_at'    => date("Y-m-d H:i:s"),
    'updated_at'    => date("Y-m-d H:i:s"),
);

MaintenanceWarehouseStock::where("date",date("Y-m-d",time()-86400))->delete();

$mdb=MainDateBase::where("status",1)->get();
foreach ($mdb as $_mdb) {//暂时锁库 不出入库以免影响统计 暂时 不做 可能统计结果出现差别

}

foreach ($mdb as $_mdb) {//对每个库 的耗材进行盘点
    $bag = array();
    $sql="select item_type,item_id,sum(current_number) number,sum(current_number*tax_purchase_price) amount from maintenance_storage_item msi
            where msi.shop_id=? and msi.status=1 and msi.type=1 and msi.data_id=?  group by msi.item_type,msi.item_id";
    $s_item=DB::select($sql,array($_mdb->shop_id,$_mdb->id));
    foreach ($s_item as $_item) {
        $input_1['item_type'] = $_item->item_type;
        $input_1['item_id'] = $_item->item_id;
        $input_1['shop_id'] = $_mdb->shop_id;
        $input_1['data_id'] = $_mdb->id;
        $input_1['number'] = $_item->number;
        $input_1['amount'] = $_item->amount;
        $bag[] = $input_1;  
        if(sizeof($bag)>2000){
            DB::table('maintenance_warehouse_stock')->insert($bag); 
            unset($bag);
            $bag=array();      
        } 
        
    }
    if(sizeof($bag)>0){
        DB::table('maintenance_warehouse_stock')->insert($bag);       
    }    
    Log::info($_mdb->name." 库耗材盘点完毕"); 
    echo $_mdb->name." 库耗材盘点完毕";
}

